package com.bsdsma.fengheguaiapp.interceptor;

import com.bsdsma.fengheguaiapp.entity.User;
import com.bsdsma.fengheguaiapp.constants.TokenConstants;
import com.bsdsma.fengheguaiapp.utils.LocalUtils;
import com.bsdsma.fengheguaiapp.utils.RedisMockUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("UserInterceptor preHandle");
        // 对于 OPTIONS 请求（CORS 预检请求）直接放行
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        Object uidObj = request.getAttribute(TokenConstants.UID);
        if(null != uidObj){
            Long uid = (Long) uidObj;
            User user = RedisMockUtils.getUser(uid);
            if(null != user){
                LocalUtils.setUser(user);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("UserInterceptor afterCompletion");
        LocalUtils.clearUser();
    }
}
